package com.hht;

import java.util.concurrent.*;

/**
 * @author hht
 * @ClassName FutureDemo
 * @Description TODO
 * @Date 2020/1/8 10:04
 * @VERSION 1.0
 */
public class FutureDemo {

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        FutureTask<Integer> res = new FutureTask<>(new FutureDemo().new CaTest(1,2));
        new Thread(res).start();
        System.out.println(res.get());
        ExecutorService executor = Executors.newFixedThreadPool(1);
        Future<Integer> future = executor.submit( new FutureDemo().new CaTest(1,2));
        System.out.println(future.get(1,TimeUnit.MILLISECONDS));


        // 创建任务T2的FutureTask
        FutureTask<String> ft2  = new FutureTask<>( new FutureDemo().new T2Task());
        // 创建任务T1的FutureTask
        FutureTask<String> ft1
                = new FutureTask<>( new FutureDemo().new T1Task(ft2));
        // 线程T1执行任务ft1
        Thread T1 = new Thread(ft1);
        T1.start();
        // 线程T2执行任务ft2
        Thread T2 = new Thread(ft2);
        T2.start();
// 等待线程T1执行结果
        System.out.println(ft1.get());

    }

    public class CaTest implements Callable<Integer> {
        private int i;
        private  int j;

        public CaTest(int i,int j){
            this.i = i;
            this.j = j;
        }

        @Override
        public Integer call() throws Exception {
            return i+j;
        }
    }





    // T1Task需要执行的任务：
// 洗水壶、烧开水、泡茶
    class T1Task implements Callable<String>{
        FutureTask<String> ft2;
        // T1任务需要T2任务的FutureTask
        T1Task(FutureTask<String> ft2){
            this.ft2 = ft2;
        }
        @Override
        public String call() throws Exception {
            System.out.println("T1:洗水壶...");
            TimeUnit.SECONDS.sleep(1);

            System.out.println("T1:烧开水...");
            TimeUnit.SECONDS.sleep(15);
            // 获取T2线程的茶叶
            String tf = ft2.get();
            System.out.println("T1:拿到茶叶:"+tf);

            System.out.println("T1:泡茶...");
            return "上茶:" + tf;
        }
    }
    // T2Task需要执行的任务:
    // 洗茶壶、洗茶杯、拿茶叶
    class T2Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("T2:洗茶壶...");
            TimeUnit.SECONDS.sleep(1);

            System.out.println("T2:洗茶杯...");
            TimeUnit.SECONDS.sleep(2);

            System.out.println("T2:拿茶叶...");
            TimeUnit.SECONDS.sleep(1);
            return "龙井";
        }
    }
}
